<template>
    <div class="box">
        <div ref="chartContainer" class="chart"></div>
    </div>
</template>
<script>
import axios from "axios";
import * as echarts from "echarts";
import {getAllPower,getDataById} from "@/api/echartApi";
export default {
  name: "HelloWorld",
  props: {
    msg: {
      type: String,
      default: "总进线",
    },
    type: {
      type: String,
      default: "AH1_IPA",
    },
    current: {
      type: String,
      default: "202.1A",
    },
    value: {
      type: Number,
      default: 202.1,
    },
    max: {
      type: Number,
      default: 202.1,
    },
    Data: {
      type: Array,
      default: () => [],
    }
  },
  data() {
    return {
      chart: null,
      powerData: [],
      timer: null,
      flag: true,
      i: 0,
      interval: 5000,
      dates: 1,
      ids: 0
    };
  },
  watch: {
    type: {
      handler(newVal) {
        // console.log(newVal);
        this.fetchPowerData(newVal);
      },
    },
  },
async  mounted() {
    // console.log(this.Data)
      this.initChart();
    await  this.fetchPowerData(this.type);
    // Update chart every 5 minutes
    this.timer = setInterval(() => {
      // this.fetchPowerData(this.type);
      this.reFetchPowerData(this.type);
      // console.log(this.powerData)
    }, 300000);
    this.resizeHandler = () => {
      this.adjustChartSize(); // Call adjustChartSize on resize
    };
    window.addEventListener("resize", this.resizeHandler);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    isMobile() {
      // Basic check using userAgent or window width
      if (
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent
        )
      ) {
        return true;
      }
      // You can also check window width as a fallback or primary method
      // return window.innerWidth <= 768;
      return false; // Default to desktop
    },
    adjustChartSize() {
      if (!this.$refs.chartContainer) return;
      const container = this.$refs.chartContainer;
      if (this.isMobile()) {
        // Set width for mobile (e.g., 100% of viewport width minus padding)
        container.style.width = "calc(100vw - 40px)"; // Adjust 40px based on parent padding
        container.style.height = "300px"; // Adjust height for mobile if needed
        console.log("手机浏览器");
        this.interval = 700;
      } else {
        // Set width for desktop (e.g., 100% of container)
        container.style.width = "100%";
        container.style.height = "500px"; // Original desktop height
        console.log("电脑浏览器");
        this.interval = 200;
      }
      // Resize the ECharts instance
      if (this.chart) {
        this.chart.resize();
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.adjustChartSize(); // Call adjustChartSize on init
      // this.updateChart(this.powerData);
    },
   async fetchPowerData(name) {
     console.log(name)
      // axios
      //   .get(`http://192.168.5.111:3001/api/users/${name}`)
      //   .then((response) => {
      //     // console.log(response.data);
      //
      //     if (this.flag === true) {
      //       this.powerData = response.data;
      //       this.updateChart(this.powerData);
      //     }
      //     // else {
      //     //   this.powerData.shift();
      //     //   this.powerData.push(response.data[response.data.length - 1]);
      //     //   console.log(response.data[response.data.length - 1]);
      //     //   this.updateChart(this.powerData);
      //     // }
      //   })
      //   .catch((error) => {
      //     console.error("Error fetching power data:", error);
      //   });
     if(this.$store.state.flag) {
       switch ( name){
         case 'AH1_IPA':
           const res = await getAllPower(name)
           this.powerData = res.data
           console.log(this.powerData)
           this.updateChart(this.powerData)
           this.$store.commit('setDataAH1',this.powerData)
           console.log(this.powerData[this.powerData.length-1].id)
           this.$store.commit('setAH1ID',this.powerData[this.powerData.length-1].id)
           break;
         case 'AH5_IPA':
           const res5 = await getAllPower(name)
           this.powerData = res5.data
           console.log(this.powerData)
           this.updateChart(this.powerData)
           this.$store.commit('setDataAH5',this.powerData)
           console.log(this.powerData[this.powerData.length-1].id)
           this.$store.commit('setAH5ID',this.powerData[this.powerData.length-1].id)
           break;
         case 'AH6_IPA':
           const res6 = await getAllPower(name)
           this.powerData = res6.data
           console.log(this.powerData)
           this.updateChart(this.powerData)
           this.$store.commit('setDataAH6',this.powerData)
           console.log(this.powerData[this.powerData.length-1].id)
           this.$store.commit('setAH6ID',this.powerData[this.powerData.length-1].id)
           break;
         case 'AH7_IPA':
           const res7 = await getAllPower(name)
           this.powerData = res7.data
           console.log(this.powerData)
           this.updateChart(this.powerData)
           this.$store.commit('setDataAH7',this.powerData)
           console.log(this.powerData[this.powerData.length-1].id)
           this.$store.commit('setAH7ID',this.powerData[this.powerData.length-1].id)
           break;
       }
     } else {
       switch ( name){
         case 'AH1_IPA':
           const res2 = await getDataById(this.$store.state.AH1ID)
           const datas = res2.data.filter(item => item.VARIANTNAME === 'AH1_IPA')
           const safeData = Array.isArray(datas) ? datas : [];
             this.powerData = [...this.$store.state.DataAH1,...safeData]
             this.updateChart(this.powerData)
           break;
         case 'AH5_IPA':
           const res5 = await getDataById(this.$store.state.AH5ID)
           const datas5 = res5.data.filter(item => item.VARIANTNAME === 'AH5_IPA')
           console.log(datas5)
           const safeData5 = Array.isArray(datas5) ? datas5 : [];
           console.log(datas5)
           this.powerData = [...this.$store.state.DataAH5,...safeData5]
             console.log(this.$store.state.DataAH5)
           this.updateChart(this.powerData)
           break;
         case 'AH6_IPA':
           const res6 = await getDataById(this.$store.state.AH6ID)
           const datas6 = res6.data.filter(item => item.VARIANTNAME === 'AH6_IPA')
           console.log(res6.data)
           const safeData6 = Array.isArray(datas6) ? datas6 : [];
             this.powerData = [...this.$store.state.DataAH6,...safeData6]
             console.log(this.$store.state.DataAH6)
           this.updateChart(this.powerData)
           break;
         case 'AH7_IPA':
           const res7 = await getDataById(this.$store.state.AH7ID)
             const datas7 = res7.data.filter(item => item.VARIANTNAME === 'AH7_IPA')
             const safeData7 = Array.isArray(datas7) ? datas7 : [];
           console.log(res7.data)
             this.powerData = [...this.$store.state.DataAH7,...safeData7]
             console.log(this.$store.state.DataAH7)
           this.updateChart(this.powerData)
           break;
       }
     }
     // if(this.$store.state.flag) {
     //   const res = await getAllPower(name)
     //   this.powerData = res.data
     //   this.updateChart(this.powerData)
     //   this.$store.commit('setDataAH1',this.powerData)
     //   this.$store.commit('setIds', this.powerData[this.powerData.length-1].id)
     //   console.log(this.$store.state.ids)
     // } else {
     //   console.log(this.$store.state.ids)
     //   const res = await getDataById(this.$store.state.ids);
     //   console.log(res)
     // }
    },
    async reFetchPowerData(name) {
      const res = await axios.get(`http://192.168.5.16:3001/api/one/${name}`);
      // console.log(res.data[0].DATA);
      this.powerData.push(res.data[0])
      this.updateChart(this.powerData)
    },
    updateChart(data) {
      // const concat = item => item.('CONCAT(RIGHT(date,6),CAST(hourF AS CHAR)'))
      // console.log(data)
      const times = data.map((item) => ((item.date).slice(2)+-+item.HOURF+':'+item.MINUTEF)) || [];
      const values = data.map((item) => (Math.trunc(item.DATA * 10) / 10).toFixed(1)) || [];
      // const times = this.datas.map(item => item.dateNum) || []
      // const values = this.datas.map(item => item.data) || []
      const option = {
        title: {
          text: this.msg,
          textAlign: "center",
          left: "50%",
        },
        tooltip: {
          trigger: "axis",
          formatter: "{b}<br />{a}: {c} A",
        },
        // grid: {
        //   right: '80%'
        // },
        xAxis: {
          type: "category",
          interval: 500000,
          data: times,
          boundaryGap: false,
          axisLabel: {
            // fontSize: 14,
            fontWeight: 'bolder',
            rotate: 45,
            showMaxLabel: true,
          },
        },
        yAxis: {
          max: this.max,
          type: "value",
          name: "电流 (A)",
          interval: 20,
          axisLabel: {
            fontSize: 14,
            // fontWeight: 'bolder'
          }
        },
        series: [
          {
            name: "电流值",
            type: "line",
            smooth: true,
            symbol: "none",
            data: values,
            progressive: 1000,
            large: true,
            largeThreshold: 2000,
            markLine: {
              symbol: "none",
              data: [
                {
                  yAxis: this.value,
                  name: "阈值A",
                  lineStyle: { color: "#f07d74", type: "solid",width:3 },
                  label: {
                    show: true, // 显示标签
                    fontSize: 14,
                    fontWeight: "bold",
                    position: "middle", // 标签位置：'start'、'middle'、'end'
                    formatter: `额定电流: ${this.current}`, // {c} 自动替换为 yAxis 值
                  },
                },
                // {
                //   yAxis: 110.45,
                //   name: '阈值B',
                //   lineStyle: { color: '#00b050', type: 'solid' },
                //   label:{
                //     show: true,   // 显示标签
                //     position: 'end', // 标签位置：'start'、'middle'、'end'
                //     formatter: '安全电流: {c}' // {c} 自动替换为 yAxis 值
                //   }
                // },
                // {
                //   type: 'max',
                //   name: '最大值',
                //   lineStyle: { color: '#ed7d31',type: 'solid' },
                //   label:{
                //     show: true,   // 显示标签
                //     position: 'end', // 标签位置：'start'、'middle'、'end'
                //     formatter: '极限电流: {c}' // {c} 自动替换为 yAxis 值
                //   }
                // },
                // {
                //   type: 'average',
                //   name: '平均电流',
                //   lineStyle: {color:'#a6a6a6', type: 'solid'},
                //   label:{
                //     show: true,
                //     position: 'end',
                //     formatter: 'A项平均电流: {c}'
                //   }
                // }
              ],
            },
          },
        ],
        grid: {
          // bottom: 100,
          left: "20%",
        },
      };

      this.chart.setOption(option);
      // let currentStart = 70
      // let currentEnd = 100
      // this.timer = setInterval(() => {
      //       // 每次向右移动 1%
      //       currentStart += 1;
      //       currentEnd += 1;

      //       // 如果超过 100%，重置到右侧（模拟连续数据）
      //       if (currentEnd > 100) {
      //           currentStart = 0;
      //           currentEnd = 70;
      //       }

      //       // 更新 dataZoom 配置
      //       this.chart.setOption({
      //           dataZoom: [{
      //               start: currentStart,
      //               end: currentEnd
      //           }]
      //       });
      //   }, 3000)
      // Handle window resize
      window.addEventListener("resize", () => {
        this.chart && this.chart.resize();
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
  height: 100%;
}
.chart {
    width: 48vw !important;
    height: 40vh !important;
}
@media (max-width: 1200px) {
  .chart {
    width: 100vw !important;
    height: 40vh !important;
  }
}
@media (max-width: 1200px) and (orientation: landscape) {
  .chart {
    width: 40vw !important;
    height: 60vh !important;
  }
}
h2 {
  text-align: center;
}
</style>
